package com.hao.service.impl;

import com.hao.dto.DailyStatisticsDTO;
import com.hao.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * 邮件服务实现类
 */
@Slf4j
@Service
public class EmailServiceImpl implements EmailService {
    
    @Autowired
    private JavaMailSender mailSender;
    
    @Value("${spring.mail.username}")
    private String fromEmail;
    
    @Value("${task.email.to}")
    private String toEmail;
    
    @Value("${task.email.subject}")
    private String subject;
    
    @Override
    public void sendStatisticsEmail(DailyStatisticsDTO statistics) {
        String content = buildStatisticsContent(statistics);
        sendSimpleEmail(toEmail, subject, content);
    }
    
    @Override
    public void sendSimpleEmail(String to, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(fromEmail);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            
            mailSender.send(message);
            log.info("邮件发送成功，收件人：{}，主题：{}", to, subject);
            
        } catch (Exception e) {
            log.error("邮件发送失败：{}", e.getMessage(), e);
        }
    }
    
    /**
     * 构建统计信息内容
     */
    private String buildStatisticsContent(DailyStatisticsDTO statistics) {
        return String.format(
            "传感器数据日报\n\n" +
            "%s\n\n" +
            "发送时间：%s\n" +
            "系统自动发送，请勿回复。",
            statistics.getStatisticsText(),
            java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
        );
    }
} 